package cn.edu.xmu.datamining.tangzk.mralgos.sssp;

import java.util.Date;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;

import cn.edu.xmu.datamining.tangzk.mralgos.AlgorithmDriver;

/**
 * Single Source Shortest Path.
 * 
 * @version 2013-8-3
 * @author tangzk
 * @Reviewer
 * 
 */
public class SingleSourceShortestPathDriver extends Configured implements Tool {

	public final static String TERM_COUNTER_GROUP = "UserDefined";
	public final static String TERM_COUNTER_NAME = "needIteration";

	@Override
	public int run(String[] args) throws Exception {
		int exitCode = 0;
		if (args.length < 2) {
			throw new Exception("Usage: <prog> <inputDir> <outputDir>");
		}
		Path inputDir = new Path(args[0]);
		String baseOutputPath = args[1];

		Configuration conf = this.getConf();
		FileSystem fs = FileSystem.get(conf);
		FileUtil.copy(fs, inputDir, fs, new Path(baseOutputPath + "-Iter0"),
				false, conf);

		Job job = null;
		long needIteration = 1;
		int iteration = 0;
		Date startTime = new Date();
		while (needIteration > 0 && exitCode == 0) {
			job = new Job(conf,
					SingleSourceShortestPathDriver.class.getSimpleName()
							+ "-Iter" + iteration);
			job.setJarByClass(SingleSourceShortestPathDriver.class);
			job.setMapperClass(SingleSourceShortestPathMapper.class);
			job.setReducerClass(SingleSourceShortestPathReducer.class);

			job.setMapOutputKeyClass(IntWritable.class);
			job.setMapOutputValueClass(GraphNodeWritable.class);
			job.setOutputKeyClass(IntWritable.class);
			job.setOutputValueClass(Text.class);

			FileInputFormat.addInputPath(job, new Path(baseOutputPath + "-Iter"
					+ iteration));
			FileOutputFormat.setOutputPath(job, new Path(baseOutputPath
					+ "-Iter" + (iteration + 1)));

			exitCode = AlgorithmDriver.runJob(job);
			needIteration = job.getCounters()
					.findCounter(TERM_COUNTER_GROUP, TERM_COUNTER_NAME)
					.getValue();
			iteration++;
		}
		Date endTime = new Date();
		System.out.println("The job total elapsed time: "
				+ (endTime.getTime() - startTime.getTime()) / (float) 1000.0
				+ " seconds.");
		return exitCode;
	}

	public static void main(String[] args) throws Exception {
		AlgorithmDriver.toolRun(new SingleSourceShortestPathDriver(), args);
	}
}
